package com.zhaoyun.ledsdk.serial;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;


/**
 * Created by suche on 2017/11/3.
 */

public class ChargeSerialHelper extends J2XXSerialHelper {

    private LuminanceListener luminanceListener;

    protected void setLuminanceListener(LuminanceListener luminanceListener) {
        this.luminanceListener = luminanceListener;
    }

    public ChargeSerialHelper(Context context, int index) {
        super(context, index);
    }

    @Override
    protected void onDataReceived(ComBean ComRecData) {
        if (luminanceListener != null) {
            luminanceListener.result(HexToAscll(MyFunc.ByteArrToHex(ComRecData.bRec)));
        }
    }

    @Override
    protected void openComPort() {
        openSerialPort();
    }

    @Override
    protected void closeComPort() {
        closeSerialPort();
    }

    protected void opneChargeSeial(int index) {
        final byte[] cmd = new byte[]{(byte) index};
        new Thread(new Runnable() {
            @Override
            public void run() {
                comSend(cmd);
            }
        }).start();
    }

    private String HexToAscll(String hex) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 2) {
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);
        }
        return sb.toString();
    }


    private synchronized void comSend(byte[] cmd) {
        sendCmd(cmd.length, cmd);
//        MyLog.d("tag", "send --> " + MyFunc.ByteArrToHex(cmd));
        SystemClock.sleep(300);
    }
}
